标签

语法如下:

{%代码段%}

for标签语法如下:

{%for item in 列表%}
循环逻辑
{{forloop.counter}}表示当前是第几次循环,从1开始
{%empty%}
列表为空或不存在时执行此逻辑
{%endfor%}

if标签语法如下:

{%if ...%}
逻辑1
{%elif ...%}
逻辑2
{%else%}
逻辑3
{%endif%}

比较运算符如下:

注意:运算符左右两侧不能紧挨变量或常量,必须有空格。

==
!=
<
>
<=
>=

布尔运算符如下:

and
or
not

点击查看内建标签了解更多标签,还有一些常用的标签会在后续地章节中讲解。

示例

1)打开booktest/views.py文件,创建视图temp_tag。

from booktest.models import BookInfo
def temp_tags(request):
    context={'list':BookInfo.objects.all()}
    return render(request,'booktest/temp_tag.html',context)

2)打开booktest/urls.py文件,配置url。

    url(r'^temp_tag/$', views.temp_tags),

3)在templates/booktest下创建temp_tag.html。



    标签


图书列表如下:
    {%for book in list%} {%if book.id <= 2%}
  • {{book.btitle}}
  • {%elif book.id <= 3%}
  • {{book.btitle}}
  • {%else%}
  • {{book.btitle}}
  • {%endif%} {%empty%}
  • 对不起,没有图书
  • {%endfor%}

4)运行服务器,在浏览器中输入如下网址。

http://127.0.0.1:8000/temp_tag/

浏览效果如下图:

标签